<?php
namespace app\controllers\supplier\uni\supplier;

use app\controllers\supplier\AdminController;
use app\models\AdminSupplier as Model;
use app\models\SupplierCategory;
use app\models\SupplierImageDesc;

class SupplierController extends AdminController
{
    // 查看资料
    public function actionView()
    {
        // 分类
        $category = SupplierCategory::find()
            ->where(['status' => 1])
            ->orderBy(['sort' => SORT_ASC, 'id' => SORT_ASC])
            ->asArray()
            ->all();

        $model = Model::find()
            ->where(['id' => $this->user->id])
            ->with(['image', 'image.image'])
            ->with(['descImage', 'descImage.image'])
            ->asArray()
            ->one();

        return $this->success([
            'categoryList' => $category,
            'model' => $model
        ]);
    }

    // 编辑简介
    public function actionEdit()
    {
        $data = $this->post();
        // $desc = $this->post('desc', '');

        $model = Model::find()
            ->where(['id' => $this->user->id])
            ->one();
        if ($model) {

            // image
            $image = SupplierImageDesc::find()
                ->where(['supplier_id' => $model->id])
                ->select(['image_id'])
                ->column();

            $image_add = array_diff($data['image'], $image);
            $image_sub = array_diff($image, $data['image']);

            $model->desc = $data['desc'];

            if ($model->save()) {

                if ($image_sub) {
                    $rs = SupplierImageDesc::deleteAll(['image_id' => $image_sub, 'supplier_id' => $model->id]);
                }
                if ($image_add) {
                    foreach ($image_add as $item) {
                        $i = new SupplierImageDesc();
                        $i->supplier_id = $model->id;
                        $i->image_id = $item;
                        $i->save();
                    }
                }

                return $this->success();
            }

        }

        return $this->fail();
    }
}